<script lang="ts" setup>
import { postPatientConsultOrderAPI } from '@/apis/common'
import {
  cancelPatientOrderAPI,
  deletePatientOrderAPI,
  getPatientConsultOrderDetailAPI,
  postPatientConsultOrderPayAPI,
} from '@/apis/consult'
import { useConsultStore } from '@/stores/consult'
import { useUserStore } from '@/stores/userStore'
import { OrderStatus, type GetPatientConsultOrderDetailData } from '@/types/consult'
import type { CustomPaymentInstance } from '@/types/global-components'
import { ref, onUnmounted } from 'vue'

const props = defineProps<{
  orderId: string
}>()

const orderDetail = ref<GetPatientConsultOrderDetailData>()

// 倒计时相关
const timeStr = ref('')
const timer = ref()

const formatTime = (time: number) => {
  const minutes = Math.floor(time / 60)
  const seconds = time % 60
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

const startCountDown = (time: number) => {
  clearInterval(timer.value)
  let count = time
  timeStr.value = formatTime(count)

  timer.value = setInterval(() => {
    count--
    if (count >= 0) {
      // 转化为整数
      timeStr.value = formatTime(count)
    } else {
      clearInterval(timer.value)
      // 倒计时结束后刷新页面
      getOrderDetail()
    }
  }, 1000)
}

const getOrderDetail = async () => {
  const res = await getPatientConsultOrderDetailAPI(props.orderId)
  console.log('订单详情', res)
  orderDetail.value = res.data
  // 如果是待支付状态且有倒计时，开始倒计时
  if (orderDetail.value?.status === OrderStatus.DaiZhiFu && orderDetail.value?.countdown) {
    startCountDown(+orderDetail.value.countdown.toFixed(0))
  }
}
getOrderDetail()
// 组件卸载时清除定时器
onUnmounted(() => {
  clearInterval(timer.value)
})

// 继续咨询
const handleContinueConsult = () => {
  uni.navigateTo({
    url: '/subpkg_consult/pages/room/room?orderId=' + props.orderId,
  })
}
// 删除订单
const handleDeleteOrder = async () => {
  const res = await uni.showModal({
    title: '提示',
    content: '确定删除该订单吗？',
    confirmColor: '#16c2a3',
  })
  if (res.confirm) {
    const res = await deletePatientOrderAPI(props.orderId)
    if (res.code === 10000) {
      uni.navigateBack()
    }
    uni.showToast({
      title: '删除成功',
      icon: 'none',
    })
  }
}
// 取消订单
const handleCancelOrder = async () => {
  const res = await uni.showModal({
    title: '提示',
    content: '确定取消该订单吗？',
    confirmColor: '#16c2a3',
  })
  if (res.confirm) {
    const res = await cancelPatientOrderAPI(props.orderId)
    if (res.code === 10000) {
      uni.navigateBack()
      uni.showToast({
        title: '取消成功',
        icon: 'none',
      })
    }
  }
}
// 咨询其它医生
const handleConsultOtherDoctor = () => {
  uni.switchTab({
    url: '/pages/index/index',
  })
}
// 支付弹窗部分-------------
const paymentPopupRef = ref<CustomPaymentInstance>()
const handleClose = async () => {
  const res = await uni.showModal({
    title: '关闭支付',
    content: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    cancelText: '仍要关闭',
    cancelColor: '#848484',
    confirmText: '继续支付',
    confirmColor: '#16C2A3',
  })

  if (res.cancel) {
    paymentPopupRef.value?.close?.()
  }
}
const handleConfirm = async (index: number) => {
  // console.log(index)
  if (index === 0) {
    // 微信支付暂不支持
    uni.showToast({ title: '微信暂不可用', icon: 'error' })
    // #ifdef MP-WEIXIN
    // 本质还是发送网络请求，获取后端返回的参数
    // 调用微信支付的 API (SDK方法)
    // wx.requestPayment(传入后端返回的支付参数)
    // #endif
  } else if (index === 1) {
    // #ifndef MP-WEIXIN
    // 支付宝支付
    const res = await postPatientConsultOrderPayAPI({
      orderId: props.orderId,
      paymentMethod: '1',
      payCallback: 'http://localhost:5173/#/subpkg_consult/pages/room/room',
    })
    console.log(res)
    location.href = res.data.payUrl
    // #endif
  }
}
const handleChange = (index: number) => {
  console.log(index)
}

const handlePay = async () => {
  paymentPopupRef.value?.open?.()
}

// 复制订单号
const handleCopyOrderNo = () => {
  if (orderDetail.value?.orderNo) {
    uni.setClipboardData({
      data: orderDetail.value.orderNo,
      success: () => {
        uni.showToast({
          title: '复制成功',
          icon: 'success',
        })
      },
    })
  }
}
</script>

<template>
  <scroll-view background-color="#f6f6f6">
    <view class="consult-page">
      <view class="page-header">
        <!-- 订单状态 -->
        <view class="order-status">
          <view class="label">
            <text class="title">图文问诊 {{ orderDetail?.actualPayment }}元</text>
            <text class="tips" v-if="orderDetail?.status === OrderStatus.YiQuXiao">
              取消/退款进度：您的订单已取消，诊金将在1-7个工作日内退回原支付账户。
            </text>
          </view>
          <text class="status">{{ orderDetail?.statusValue }}</text>
        </view>
        <!--  医生信息 -->
        <view class="consult-doctor">
          <text class="lable">服务医生信息</text>
          <view class="doctor">
            <image class="doctor-avatar" src="/static/uploads/doctor-avatar.jpg" />
            <view class="doctor-info">
              <view class="meta">
                <text class="name">王医生</text>
                <text class="title">内分泌科 | 主任医师</text>
              </view>
              <view class="meta">
                <text class="tag">三甲</text>
                <text class="hospital">积水潭医院</text>
              </view>
            </view>
            <view class="arrow">
              <uni-icons size="18" color="#C3C3C5" type="forward" />
            </view>
          </view>
        </view>
      </view>
      <!-- 患者信息 -->
      <view class="consult-patient">
        <uni-list :border="false">
          <uni-list-item
            title="患者信息"
            :right-text="
              orderDetail?.patientInfo?.name +
              ' | ' +
              orderDetail?.patientInfo?.genderValue +
              ' | ' +
              orderDetail?.patientInfo?.age +
              '岁'
            "
          />
          <uni-list-item title="病情描述" :note="orderDetail?.illnessDesc" />
        </uni-list>
      </view>

      <!-- 订单信息 -->
      <view class="order-info">
        <uni-list :border="false">
          <uni-list-item title="订单编号">
            <template #footer>
              <view class="order-no-wrapper">
                <text>{{ orderDetail?.orderNo }}</text>
                <button class="copy-btn" size="mini" @click="handleCopyOrderNo">复制</button>
              </view>
            </template>
          </uni-list-item>
          <uni-list-item title="创建时间" :right-text="orderDetail?.createTime" />
          <uni-list-item
            title="取消时间"
            v-if="orderDetail?.status === OrderStatus.YiQuXiao"
            :right-text="orderDetail?.createTime"
          />
          <uni-list-item title="应付款" right-text="¥49" />
          <uni-list-item title="优惠券">
            <template #footer>
              <view class="uni-list-text-red">-¥{{ orderDetail?.couponDeduction }}</view>
            </template>
          </uni-list-item>
          <uni-list-item title="积分抵扣">
            <template #footer>
              <view class="uni-list-text-red">-¥{{ orderDetail?.pointDeduction }}</view>
            </template>
          </uni-list-item>
          <uni-list-item title="实付款">
            <template #footer>
              <view class="uni-list-text-red">¥{{ orderDetail?.actualPayment }}</view>
            </template>
          </uni-list-item>
          <uni-list-item
            title="支付时间"
            v-if="orderDetail?.status === OrderStatus.YiWanCheng"
            :right-text="orderDetail?.createTime"
          />
        </uni-list>
      </view>

      <view class="notice-bar">
        <uni-notice-bar
          v-if="orderDetail?.status === OrderStatus.DaiZhiFu"
          :text="`请在 ${timeStr} 内完成支付，超时订单将取消`"
        />
      </view>

      <!-- 底部 -->
      <view class="toolbar">
        <template v-if="orderDetail?.status === OrderStatus.DaiZhiFu">
          <view class="total-amount">
            需付款: <text class="number">¥{{ orderDetail?.actualPayment }}</text>
          </view>
          <view class="buttons">
            <button class="uni-button minor" @click="handleCancelOrder">取消问诊</button>
            <button class="uni-button" @click="handlePay">立即支付</button>
          </view>
        </template>
        <template v-else-if="orderDetail?.status === OrderStatus.YiWanCheng">
          <view class="buttons">
            <view class="delete-botton" @click="handleDeleteOrder">
              <uni-icons size="24" color="#848484" type="trash" />
              <text>删除订单</text>
            </view>
            <button class="uni-button" @click="handleConsultOtherDoctor">咨询其它医生</button>
          </view>
        </template>
        <template v-else-if="orderDetail?.status === OrderStatus.YiQuXiao">
          <view class="buttons">
            <button class="uni-button" @click="handleDeleteOrder">删除订单</button>
          </view>
        </template>
        <template v-else-if="orderDetail?.status === OrderStatus.ZiXunZhong">
          <view class="buttons">
            <button class="uni-button" @click="handleContinueConsult">继续咨询</button>
          </view>
        </template>
        <template v-else-if="orderDetail?.status === OrderStatus.DaiJieZhen">
          <view class="buttons">
            <view class="delete-botton" @click="handleCancelOrder">
              <uni-icons size="24" color="#848484" type="trash" />
              <text>取消问诊</text>
            </view>
            <button class="uni-button" @click="handleContinueConsult">继续咨询</button>
          </view>
        </template>
      </view>
    </view>
    <custom-payment
      ref="paymentPopupRef"
      :order-id="orderId"
      :amount="orderDetail?.actualPayment ?? 0"
      @close="handleClose"
      @confirm="handleConfirm"
      @change="handleChange"
    />
  </scroll-view>
</template>

<style lang="scss">
@import './index.scss';

.order-no-wrapper {
  display: flex;
  align-items: center;
  gap: 10rpx;

  .copy-btn {
    font-size: 20rpx;
    background-color: #f6f6f6;
    border: 1px solid #16c2a3;
    border-radius: 30rpx;
    color: #16c2a3;
  }
}
</style>
